package com.xiguaji.tiktok.v1.ins.blogger.repository.impl;

import com.xiguaji.boot.toolkit.jdbc.JdbcTemplateHelper;
import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.v1.ins.blogger.dto.InsTaggerBloggerReq;
import com.xiguaji.tiktok.v1.ins.blogger.dto.InsTaggerBloggerResp;
import com.xiguaji.tiktok.v1.ins.blogger.repository.InsBloggerExtRepository;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class InsBloggerExtRepositoryImpl implements InsBloggerExtRepository {

    public Page<InsTaggerBloggerResp> findTaggerBloggerPage(InsTaggerBloggerReq insTaggerBloggerReq,long startTime,long endTime){
        String selectSql = "select a.* ";
        String fromSql = " from (" +
                "select count(*) count,b.uid,b.username,b.full_name," +
                "b.overall_category_name,b.category_name,b.pic_url," +
                "b.following_count,sum(m.like_count + m.comment_count) engagements," +
                "avg(m.er) avg_er " +
                "from ins_rel_media_tagger_user mtu " +
                "left join ins_blogger_main b " +
                "on mtu.uid = b.uid " +
                "left join ins_media m " +
                "on mtu.shortcode = m.shortcode " +
                "where mtu.tagger_uid = ? and " +
                "{}" +
                "mtu.taken_time between ? and ? group by mtu.uid) a " +
                "order by a.following_count";
        String categorySql = "";
        List<Object> params = new ArrayList<>();
        params.add(insTaggerBloggerReq.getUid());

        if(!StringUtils.isEmpty(insTaggerBloggerReq.getCategory())){
            categorySql = " b.overall_category_name = ? ";
            params.add(insTaggerBloggerReq.getCategory());
        }
        fromSql = fromSql.replace("{}",categorySql);
        params.add(startTime);
        params.add(endTime);

        return JdbcTemplateHelper.paginate(InsTaggerBloggerResp.class,insTaggerBloggerReq.getPage(),insTaggerBloggerReq.getPageSize(),selectSql,fromSql,params.toArray());
    }
}
